import { mapGetters } from 'vuex';
import { getUserDetailApi, createOrEditUserApi, getByCodeApi, getRoleListApi, getSysStructsTreeApi, getDictionaryDataListApi } from './create-user.service'
import { alertMessage, alertHtmlWithCallback, getTreeData, showAlertMessage, securityPhone } from '@/utils/utils';
export default {
  name: 'create-user',
  components: {},
  directives: {},
  props: {
    userId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      file_url: process.env.VUE_APP_FILE_URL, // 头像url
      loading: false, // table loading
      showDialog: true, // 是否显示弹窗
      title: '创建用户',
      roles: [], // 职位列表
      structs: [], // 部门树
      status: [], // 用户状态
      // 创建/编辑弹窗
      editForm: {
        isEnable: 1,
        sex: '男'
      }, // 编辑用户表单
      editRules: {
        userName: [
          { required: true, message: '此项为必填项', trigger: "blur" },
          { pattern: /^[a-zA-Z0-9]+$/, message: '此项限字母或数字', trigger: 'blur' },
          { min: 1, max: 6, message: '此项长度限6位', trigger: 'blur' }
        ],
        trueName: [
          { required: true, message: '此项为必填项', trigger: "blur" },
          { pattern: /^[a-zA-Z0-9\u4E00-\u9FFF]+$/, message: '此项限字母,数字或汉字', trigger: 'blur' },
          { min: 1, max: 5, message: '此项长度限5位', trigger: 'blur' }
        ],
        mobileNumber: [
          { required: true, message: '此项为必填项', trigger: "blur" },
          { pattern: /^1(1|2|3|4|5|6|7|8|9|0)\d{9}$/, message: '手机号格式不正确', trigger: "blur" }
        ],
        roleObj: [{ required: true, message: '此项为必填项', trigger: 'blur' }],
        structId: [{ required: true, message: '此项为必填项', trigger: "blur" }],
        structCode: [
          { required: true, message: '此项为必填项', trigger: "blur" },
          { pattern: /^[a-zA-Z0-9]+$/, message: '此项限字母或数字', trigger: 'blur' },
          { min: 1, max: 6, message: '此项长度限6位', trigger: 'blur' }
        ],
        remark: [
          { min: 1, max: 20, message: '此项长度限20位', trigger: 'blur' }
        ],
        enumStatus: [
          { required: true, message: '此项为必填项', trigger: "change" }
        ]
      }, // 编辑表单验证规则
      defaultProps: { // 级联选择器
        checkStrictly: true,
        label: 'name',
        value: 'objectId',
        emitPath: false
      }
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    this.getSysStruct();
    this.getDictionaryDataList();
    if (this.userId) {
      this.title = '编辑用户';
      this.getUserDetail();
    }
  },
  methods: {
    // 获取部门列表
    getSysStruct() {
      getSysStructsTreeApi().then(res => {
        this.structs = getTreeData(res.data);
      });
    },

    // 获取详情
    getUserDetail() {
      getUserDetailApi(this.userId).then(async res => {
        this.roles = await this.getSysRole();
        const rolesName = res.data.roleNames.split(',')
        res.data.roleObj = res.data.roleIds.map((v, index) => ({ objectId: v, name: rolesName[index] }))
        this.editForm = res.data;
      })
    },

    // 选择部门
    chooseStruct() {
      this.$set(this.editForm, 'structName', this.$refs.cascades.getCheckedNodes()[0].pathLabels.join('-'));
      this.$set(this.editForm, 'structCode', this.$refs.cascades.getCheckedNodes()[0].data.code);
      this.validateStruct()
    },

    // 搜索部门
    searchStruct() {
      if (!this.editForm.structCode) {
        this.$set(this.editForm, 'structId', '');
        this.$set(this.editForm, 'structName', '');
        return
      }
      getByCodeApi(this.editForm.structCode).then(res => {
        this.$set(this.editForm, 'structId', res.data.objectId);
        this.$nextTick(() => {
          this.$set(this.editForm, 'structName', this.$refs.cascades.getCheckedNodes()[0].pathLabels.join('-'));
          this.validateStruct()
        })
      })
    },

    // 职位远程搜索
    async remoteMethod(query) {
      this.roles = await this.getSysRole(query)
    },

    // 获取职位列表(角色)
    getSysRole(queryStr) {
      const data = {
        queryStr: queryStr,
        pageNum: 1,
        recordNum: 20
      }
      return new Promise(resolve => {
        getRoleListApi(data).then(res => {
          const roles = res.data
          resolve(roles)
        })
      })
    },

    // 获取字典列表-用户状态
    getDictionaryDataList() {
      this.loading = false;
      const postBody = {
        tableName: 'sys_user.enum_status'
      }
      getDictionaryDataListApi(postBody).then(res => {
        this.status = res.data;
        // 创建默认赋值
        if (!this.userId) {
          this.$set(this.editForm, 'enumStatus', '10')
        }
        this.loading = false;
      });
    },

    // 限制上传图片格式
    beforeAvatarUpload(file) {
      const isPhoto = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isPhoto) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      return isPhoto;
    },

    // 上传头像
    handleAvatarSuccess(res, file) {
      this.$set(this.editForm, 'headImgUrl', res.data)
    },

    // 删除头像
    handleAvatarRemove() {
      this.editForm.headImgUrl = '';
    },

    // 保存
    save() {
      this.editForm.roleIds = this.editForm.roleObj.map(v => v.objectId)
      let postData = JSON.parse(JSON.stringify(this.editForm));
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const message = {
            userName: this.editForm.userName,
            trueName: this.editForm.trueName,
            mobileNumber: securityPhone(this.editForm.mobileNumber),
            roleNames: this.editForm.roleObj.map(v => v.name).join('&nbsp;&nbsp;'),
            sex: this.editForm.sex,
            structName: this.editForm.structName,
            structCode: this.editForm.structCode
          }
          const alertMsg = showAlertMessage(`请确认${!this.userId ? '创建' : '编辑'}内容`, message)
          alertHtmlWithCallback(alertMsg, `确认要${!this.userId ? '创建' : '编辑'}这条信息吗?`).then(yes => {
            if (yes) {
              this.loading = true;
              createOrEditUserApi(postData).then(res => {
                alertMessage(res.message);
                this.closeDialog();
                this.loading = false;
                this.$emit('reload', true);
              }).catch(() => {
                this.loading = false;
              })
            }
          })
        } else {
          return false;
        }
      });
    },

    // 表单校验
    validateStruct() {
      this.$refs.dataForm.validateField('structId');
      this.$refs.dataForm.validateField('structCode');
    },

    // 表单校验
    validateRole() {
      this.$refs.dataForm.validateField('roleObj');
    },

    // 关闭dialog时需要告诉父组件隐藏弹窗
    closeDialog() {
      this.showDialog = false;
      this.$emit('close', true);
    }
  }
}
